package com.iz0000.exp.ssmeh;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Auther: guoxl
 * @Date: 2019/4/8 01:59
 * @Description:
 */
public class LockableQueue<T, v> {

    private Map<T, v> map = new HashMap<>();//共享数据，只能有一个线程能写该数据，但可以有多个线程同时读该数据。
    private ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();

    public v get(String s) {
        rwl.readLock().lock();
        try {
            System.out.println("get --> " + s);
            return map.get(s);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            rwl.readLock().unlock();
        }
    }

    public void set(T key, v val){
        rwl.writeLock().lock();//上写锁，不允许其他线程读也不允许写
        try {
            System.out.println("set --> " + key);
            map.put(key, val);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            rwl.writeLock().unlock();//释放写锁
        }
    }


    public static void main(String[] args) {
        LockableQueue<String, String> queue = new LockableQueue();
        ExecutorService pool = Executors.newFixedThreadPool(20);

        for (int i = 0; i < 50; i++) {
            pool.submit(() ->{

                    try {
                        Thread.sleep(10000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    queue.set("system-time", System.currentTimeMillis() + "");
                });
        }

        for (int i = 0; i < 50; i++) {
            pool.submit(() -> {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                String o = queue.get("system-time");
            });
        }


    }
}
